#include "cplayer.h"

void cplayer::update (){
	if (carts.size()!=ie(GSI_CARTS_NUM)){
		if (carts.size()>ie(GSI_CARTS_NUM))
			carts.resize(ie(GSI_CARTS_NUM));
		while (carts.size()<ie(GSI_CARTS_NUM)){
			if (carts.size()==0){
				carts.push_back(new obj_cart_front());
				carts[carts.size()-1]->x=0;
				carts[carts.size()-1]->y=4;
				carts[carts.size()-1]->rot=0;
				carts[carts.size()-1]->mass=1;
			}
			else{
				carts.push_back(new obj_cart_truck());
				carts[carts.size()-1]->x=carts[carts.size()-2]->x-cos(carts[carts.size()-2]->rot)*(CART_LENGHT+1);
				carts[carts.size()-1]->y=carts[carts.size()-2]->y-sin(carts[carts.size()-2]->rot)*(CART_LENGHT+1);
				carts[carts.size()-1]->rot=carts[carts.size()-2]->rot;
				carts[carts.size()-1]->mass=0.05;
			}
		}
	
	}
	carts[0]->update((((kb(KB_FORWARD)&KB_STATUS_PRESSED)!=0)-((kb(KB_BACKWARD)&KB_STATUS_PRESSED)!=0)),
	(((kb(KB_LEFT)&KB_STATUS_PRESSED)!=0)-((kb(KB_RIGHT)&KB_STATUS_PRESSED)!=0)));
	for(int i=1;i<carts.size();i++)
		carts[i]->update(0,0);

	FOR(i, carts.size())
		for (int j = i+1;j<carts.size();j++){
//			debug("colliding carts %d %d",i,j);
//			carts[i]->chcollide(*carts[j]);
		}

	for(int i=1;i<carts.size();i++)
		carts[i]->joint_push(*carts[i-1]);
}

void cplayer::draw (){

	if (kb(KB_M1)){
		debug ("Kreslim polohu mysi %f %f hrac: %f %f",kb_wx(),kb_wy(),carts[0]->x,carts[0]->y);
		
		glColor3ub(0,0,0);
		glPointSize(5.);
		glBegin(GL_POINTS);
			glVertex3f(kb_wx(),kb_wy(),0.9);
			glVertex3f(carts[0]->x,carts[0]->y,0.9);
		glEnd();
		glColor3ub(255,255,255);
	}
	
	FOR (i,carts.size())
		carts[i]->draw_cart();
}

void cplayer::collide(obj & col){
	if (carts.size()==0)
		return;

	if ((col.x-carts[(carts.size()-1)/2]->x)*(col.x-carts[(carts.size()-1)/2]->x)+(col.y-carts[(carts.size()-1)/2]->y)*(col.y-carts[(carts.size()-1)/2]->y)
		>(CART_LENGHT*carts.size()/2+col.r)*(CART_LENGHT*carts.size()/2+col.r))
		return;

	FOR(i, carts.size())
		carts[i]->chcollide(col);

}
